import DexieCtx from '@/utils/dexiectx';
import Config from '@/utils/config';
import { Api, TelegramClient } from 'telegram'
import { StringSession } from 'telegram/sessions'
import IpcParams from '@/ipc/IpcParams';

class HamsterTgweb {
  constructor() {
    this.isRunning = false
  }

  async allRun() {
    this.isRunning = true
    const dexie = await DexieCtx.db()
    const allAccounts = await dexie.accounts.where("session").notEqual("").toArray()
    // for (let index = 0; index < allAccounts.length; index++) {
    //   const element = allAccounts[index];
    //   try {
    //     const acCopy = { ...element, platform: "ios", bot: "hamster_kombat_bot", url: "https://hamsterkombatgame.io/" }
    //     const params = new IpcParams("requestTgwebUrl", acCopy)
    //     const tgwebUrl = await window.gameAPI.invoke(params)
    //     console.log(tgwebUrl)
    //     // todo with url
    //   } catch (error) {
    //     console.error(error)
    //   }
    // }
    // return
    const allClients = allAccounts.map(item => {
      const strSession = new StringSession(item.session)
      const client = new TelegramClient(strSession, Config.API_ID, Config.API_HASH, {
        connectionRetries: 3,
        useWSS: true,
        timeout: 20,
      })
      client.phone = item.phone
      return client
    })
    let index = 0;
    let step = 10;
    while (index < allClients.length) {
      try {
        let promises = []
        for (let i = index; i < index + step; i++) {
          if (i >= allClients.length) {
            break;
          }
          const client = allClients[i]
          const prms = this.run(client, dexie)
          promises.push(prms)
        }
        await Promise.allSettled(promises)
        console.log(Date() + " finished " + index + "~" + (index + step))
        index += step
      } catch (error) {
        console.error(error)
        continue
      }
    }
    this.isRunning = false
  }

  async run(client, dexie) {
    try {
      await client.connect();
      const isAuth = await client.checkAuthorization()
      if (isAuth != true) {
        throw new Error("unauth");
      }
      const user = await client.getInputEntity('hamster_kombat_bot');
      const result = await client.invoke(
        new Api.messages.RequestWebView({
          peer: user,
          bot: "hamster_kombat_bot",
          fromBotMenu: true,
          url: "https://hamsterkombatgame.io/",
          platform: "android"
        })
      );

      const url = result.url;
      await this.updateHamsterTable(client.phone, url, dexie)
    } catch (error) {
      if (error.message == 'unauth') {
        console.log(client.phone, "TG未登录")
        // await dexie.hamster.where('phone').equals(client.phone).delete()
        // await dexie.accounts.where('phone').equals(client.phone).modify({
        //   session: null
        // })
      }
    } finally {
      try {
        await client.disconnect()
        await client.destroy()
      } catch (error) {
      }
    }

  }

  async updateHamsterTable(phone, tgweb, dexie) {
    const oldValue = await dexie.hamster.get({
      phone: phone
    })
    const dateStr = (new Date()).toLocaleString()
    if (oldValue == null) {
      await dexie.hamster.add({
        phone,
        tgweb: tgweb,
        tokenupdate: dateStr,
      })
    } else {
      await dexie.hamster.where("phone").equals(phone).modify({
        tgweb: tgweb,
        tokenupdate: dateStr,
      })
    }
  }
}

export default HamsterTgweb